/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
 *
 * @author Trungnm
 */
public class Login extends HttpServlet {
    private boolean bFound = false;
    private final String invalidPage = "invalidPage.jsp";
    private final String homePage = "DefaultController?action=view_all_album";
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException, TransformerException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String action = request.getParameter("login");
            if(action.equals("Login")){
                String username = request.getParameter("username");
                String password = request.getParameter("pwd");

                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = null;
                try {
                    db = dbf.newDocumentBuilder();
                } catch (ParserConfigurationException ex) {
                    ex.printStackTrace();
                }
                String realPath = getServletContext().getRealPath("/");
                String filePath = realPath + "WEB-INF/account.xml";
                Document doc = db.parse(new File(filePath));

                XPathFactory xpf = XPathFactory.newInstance();
                XPath xpath = xpf.newXPath();
                String expression = "//student[normalize-space(username)='" + username +
                        "' and normalize-space(password)='" + password + "']";
                Boolean result = (Boolean) xpath.evaluate(expression, doc, XPathConstants.BOOLEAN);

                String url = invalidPage;
                if(result.booleanValue()){
                    url = homePage;
                    HttpSession session = request.getSession();
                    session.setAttribute("username", username);
                }

                RequestDispatcher rd = request.getRequestDispatcher(url);
                rd.forward(request, response);
                try {
                    db = dbf.newDocumentBuilder();
                } catch (ParserConfigurationException ex) {
                    ex.printStackTrace();
                }
            }else if(action.equals("Create")){
                String username = request.getParameter("username");
                String password = request.getParameter("password");

                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = null;
                try {
                    db = dbf.newDocumentBuilder();
                } catch (ParserConfigurationException ex) {
                    ex.printStackTrace();
                }
                String realPath = getServletContext().getRealPath("/");
                String filePath = realPath + "WEB-INF/account.xml";
                Document doc = db.parse(new File(filePath));

                //bFound = false;
                //insertStudent(doc, username);
                //String url = "Controller?btAction=Search&txtName=" + name;
                if(bFound){
                    writeXML(doc, filePath);
                }
                //response.sendRedirect(url);
            }

        } catch (XPathExpressionException ex) {
            ex.printStackTrace();
        } catch (SAXException ex) {
            ex.printStackTrace();
        } finally {
            out.close();
        }
    }

    private void checkLogin(Node node, String username, String password){
        if(node == null || bFound) {
            return;
        }
        if(node.getNodeName().equals("username")){
            String sUser = node.getTextContent();
            if(sUser.trim().equals(username)){
                Node sibling = node.getNextSibling();
                while(!sibling.getNodeName().equals("password")){
                    sibling = sibling.getNextSibling();
                }
                String sPass = sibling.getTextContent();
                if(sPass.trim().equals(password)){
                    bFound = true;
                }
            }
        }
        NodeList children = node.getChildNodes();
        int i = 0;
        while (i<children.getLength()){
            checkLogin(children.item(i++), username, password);
        }
    }
    private void writeXML(Node node, String fileName) throws TransformerException{
        try {
            TransformerFactory tff = TransformerFactory.newInstance();
            DOMSource source = new DOMSource(node);
            StreamResult result = new StreamResult(new File(fileName));
            Transformer trans = tff.newTransformer();
            trans.setOutputProperty(OutputKeys.INDENT, "yes");
            trans.transform(source, result);
        } catch (TransformerConfigurationException ex) {
            ex.printStackTrace();
        } catch (TransformerException ex) {
            ex.printStackTrace();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (TransformerException ex) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        }
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (TransformerException ex) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
